<?php
namespace app\store\model\project;

use app\common\model\BaseModel;

class Project extends BaseModel{
    protected $autoWriteTimestamp = true;

    // 关联疾病类型
    public function illness(){
        return $this->hasOne(Illness::class,'id','type_illness')
            ->bind(['tag']);
    }

    // 关联所属医院
    public function hospital(){
        return $this->hasOne(Hospital::class,'id','hospital_id')
            ->bind([
                'province_h'=>'province',
                'city_h'=>'city',
                'area_h'=>'area',
                'name_h'=>'name'
            ]);
    }

    // 获取剩余天数
    public function getDelydayAttr($value,$data){
        $endTime = $data['end_time'];
        $second = $endTime - time();
        if($second < 0) {
            return 0;
        }else{
            $delayData = floor($second/86400);
            // 有余数则大于一天
            if($second%86400 > 1){
                $delayData += 1;
            }
            return $delayData;
        }
    }
    // 项目列表
    public function getList(array $data){
        $filter = $this->getFilter($data);
        /*$where = [];
        $current_time = time();
        // 按创建日期选择
        if(isset($data['create_day'])){
            $where['create_day'] = $data['create_day'];
        }
        // 根据地区进行选择
        if(isset($data['province']) && isset($data['city']) && isset($data['area'])){
            $where['province'] = $data['province'];
            $where['city'] = $data['city'];
            $where['area'] = $data['area'];
        }
        // 补助大于多少金额
        if(isset($data['allowance'])){
            $where['allowance'] = ['>=',$data['allowance']];
        }
        // 周期(天)
        if(isset($data['scope_day'])){
            $where['create_day'] = ['>=',date('Ymd',$current_time)+$data['scope_day']];
        }
        // 是否热门项目
        if (isset($data['is_heat'])){
            $where['is_heat'] = 1;
        }*/

        return $this->where(['is_delete'=>0])
            ->with(['illness','hospital'])
            ->where($filter)
            ->append(['delyday'])
            ->paginate(15);
    }

    // 获取项目单条记录
    public static function detail(int $id){
        $r = self::where(['id'=>$id])->with(['illness','hospital'])->find();
        if($r->isEmpty()){
            throwError('没有找到项目');
        }
        $wherein = "{$r['province']},{$r['city']},{$r['area']}";
        $res = (new Region)->whereIn('name',$wherein)->select();
        $r['address'] = [$res[0]['id'],$res[1]['id'],$res[2]['id']];
        return $r;
    }

    // UTC时间格式转UNIX时间戳
    private static function UTCtoUNIX(string $utc){
        $time= str_replace(array('T','Z'),' ',$utc);
        return strtotime($time);
    }

    // 创建项目
    public static function add(array $data){
        $wherein = implode(',',$data['address']);
        $cityR = (new Region)->whereIn('id',$wherein)->select();
        $create_day = date('Ymd');

        $dataW = [
            'store_id' => getStoreId(),
            'title' => $data['title'],
            'type_project' => $data['type_project'],
            'type_illness' => $data['type_illness'],
            'allowance' => $data['allowance'],
            'out_award' => $data['out_award'],
            'gold' => $data['gold'],
            'transport_gold' => $data['transport_gold'],
            'start_time' => self::UTCtoUNIX($data['start_time']),
            'end_time' => self::UTCtoUNIX($data['end_time']),
            'sex' => $data['sex'],
            'age_min' => $data['age_min'],
            'age_max' => $data['age_max'],
            'is_smoke' => $data['is_smoke'],
            'be_in_day' => $data['be_in_day'],
            'hospital_id' => $data['hospital_id'],
            'hospital_id_other' => json_encode($data['hospital_id_other']),
            'intro' => $data['intro'],
            'copy' => $data['copy'],
            'arrangement' => $data['arrangement'],
            'earnings_remark' => $data['earnings_remark'],

            'province' => $cityR[0]['name'],
            'city' => $cityR[1]['name'],
            'area' => $cityR[2]['name'],

            'is_heat' => $data['is_heat'],
            'create_day' => $create_day
        ];
        return self::create($dataW);
    }

    // 修改项目
    public static function edit(array $data){
        $wherein = implode(',',$data['address']);
        $cityR = (new Region)->whereIn('id',$wherein)->select();
        return self::update([
            'store_id' => getStoreId(),
            'title' => $data['title'],
            'type_project' => $data['type_project'],
            'type_illness' => $data['type_illness'],
            'allowance' => $data['allowance'],
            'out_award' => $data['out_award'],
            'gold' => $data['gold'],
            'transport_gold' => $data['transport_gold'],
            'start_time' => self::UTCtoUNIX($data['start_time']),
            'end_time' => self::UTCtoUNIX($data['end_time']),
            'sex' => $data['sex'],
            'age_min' => $data['age_min'],
            'age_max' => $data['age_max'],
            'is_smoke' => $data['is_smoke'],
            'be_in_day' => $data['be_in_day'],
            'hospital_id' => $data['hospital_id'],
            'hospital_id_other' => json_encode($data['hospital_id_other']),
            'intro' => $data['intro'],
            'copy' => $data['copy'],
            'arrangement' => $data['arrangement'],
            'earnings_remark' => $data['earnings_remark'],

            'province' => $cityR[0]['name'],
            'city' => $cityR[1]['name'],
            'area' => $cityR[2]['name'],

            'is_heat' => $data['is_heat']
        ],['id'=>$data['id']]);
    }

    // 删除项目
    public static function del(array $data){
        return self::where(['id'=>$data['id']])->delete();
    }

    /**
     * 设置查询条件
     * @param array $param
     * @return array
     */
    private function getFilter(array $param): array
    {
        // 设置默认的检索数据
        $params = $this->setQueryDefaultValue($param, [
            'userId' => 0,          // 会员ID
            'search' => '',         // 搜索内容
            'betweenTime' => [],    // 起止时间
        ]);
        // 检索查询条件
        $filter = [];
        // 搜索内容: 用户昵称
        !empty($params['search']) && $filter[] = ['title', 'like', "%{$param['search']}%"];
        // 起止时间
        if (!empty($params['betweenTime'])) {
            $times = between_time($params['betweenTime']);
            $filter[] = ['create_time', '>=', $times['start_time']];
            $filter[] = ['create_time', '<', $times['end_time'] + 86400];
        }
        return $filter;
    }
}
